package com.computergames.server.server.handler;

import com.computergames.server.domain.ClientState;
import com.computergames.server.message.ErrorResponseMessage;
import com.computergames.server.server.session.RoomSessionFactory;
import com.computergames.server.server.session.RoomSessionService;
import com.computergames.server.service.Interface.CheckAndUpdateClientState;
import com.computergames.server.util.SpringUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import com.computergames.server.server.session.SessionFactory;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

@ChannelHandler.Sharable
@Slf4j
public class QuitHandler extends ChannelInboundHandlerAdapter {
    private static final AttributeKey<String> USER_ROOM_KEY = AttributeKey.valueOf("USER_ROOM");
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        CheckAndUpdateClientState checkAndUpdateClientState = SpringUtil.getBean(CheckAndUpdateClientState.class);
        String roomName = (String)ctx.attr(AttributeKey.valueOf("USER_ROOM")).get();
        String username = SessionFactory.getSession().getUsername(ctx.channel());
        if(checkAndUpdateClientState.checkState(ctx, ClientState.GAME_ENDED)){
            // 使房间名与通道解绑
            ctx.channel().attr(USER_ROOM_KEY).set(null);
            RoomSessionService roomSessionService = RoomSessionFactory.getRoomSession();
            roomSessionService.removeMember(roomName, username);
            SessionFactory.getSession().unbind(ctx.channel());
        }
        log.info("{}连接断开", username);

        //checkAndUpdateClientState.removeState(ctx.channel());
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        CheckAndUpdateClientState checkAndUpdateClientState = SpringUtil.getBean(CheckAndUpdateClientState.class);
        String roomName = (String)ctx.attr(AttributeKey.valueOf("USER_ROOM")).get();
        String username = SessionFactory.getSession().getUsername(ctx.channel());
        if(checkAndUpdateClientState.checkState(ctx, ClientState.GAME_ENDED)){
            // 使房间名与通道解绑
            ctx.channel().attr(USER_ROOM_KEY).set(null);
            RoomSessionService roomSessionService = RoomSessionFactory.getRoomSession();
            roomSessionService.removeMember(roomName, username);
            SessionFactory.getSession().unbind(ctx.channel());
        }
        ctx.writeAndFlush(new ErrorResponseMessage(cause.getMessage()));
        //checkAndUpdateClientState.removeState(ctx.channel());
        //SessionFactory.getSession().unbind(ctx.channel());
        log.info("{}连接异常, 异常是{}", username, cause.getMessage());
    }
}
